package com.corner.system.service.impl;

import com.corner.common.constant.CacheConstants;
import com.corner.common.constant.Constants;
import com.corner.common.core.domain.entity.SysUser;
import com.corner.common.core.domain.model.LoginUser;
import com.corner.common.core.redis.RedisCache;
import com.corner.common.exception.GlobalException;
import com.corner.common.exception.user.CaptchaException;
import com.corner.common.exception.user.CaptchaExpireException;
import com.corner.common.utils.MessageUtils;
import com.corner.common.utils.StringUtils;
import com.corner.system.domain.*;
import com.corner.system.domain.vo.EditUserInfoValuesVo;
import com.corner.system.domain.vo.EditUserInfoVo;
import com.corner.system.mapper.*;
import com.corner.system.service.FarmerUserService;
import org.apache.ibatis.annotations.Case;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 农户业务层处理
 * 
 * @author corner
 */
@Service
public class FarmerUserServiceImpl implements FarmerUserService
{
    private static final Logger log = LoggerFactory.getLogger(FarmerUserServiceImpl.class);

    @Autowired
    private FarmerUserMapper farmerUserMapper;
    @Autowired
    private OperationLogMapper operationLogMapper;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SysUserMapper userMapper;



    @Transactional
    @Override
    public void editUserInfo(EditUserInfoVo editUserInfoVo, SysUser user) throws Exception {

        if(editUserInfoVo.getFarmerId() == null){
            throw new GlobalException("farmerId为空！");
        }
        if(editUserInfoVo.getFarmerName() == null){
            throw new GlobalException("farmerName为空！");
        }
        if(editUserInfoVo.getOperationWay() == null){
            throw new GlobalException("OperationWay为空！");
        }
        if(editUserInfoVo.getOperationType() == null){
            throw new GlobalException("OperationType为空！");
        }
        if (editUserInfoVo.getEditUserInfoValuesVos() == null || editUserInfoVo.getEditUserInfoValuesVos().size() == 0){
            throw new GlobalException("更新数据EditUserInfoValuesVos为空！");
        }

        OperationLog operationLog = new OperationLog();
        FarmerUser farmerUser = new FarmerUser();
        StringBuffer sb = new StringBuffer();

        farmerUser.setFarmerId(editUserInfoVo.getFarmerId());
        operationLog.setFarmerUserId(editUserInfoVo.getFarmerId());
        operationLog.setOperatorId(user.getUserId());
        operationLog.setOperatorName(user.getUserName());
        operationLog.setOperationTime(new Date());
        operationLog.setOperationType(editUserInfoVo.getOperationType());
        operationLog.setOperationWay(editUserInfoVo.getOperationWay());

        sb.append("用户："+ editUserInfoVo.getFarmerName()+" 通过");

        String operationWay = editUserInfoVo.getOperationWay();
        if("1".equals(operationWay)){
            sb.append("公众号，");
        }else if("2".equals(operationWay)){
            sb.append("服务热线，");
        }


        List<EditUserInfoValuesVo> editUserInfoValuesVos = editUserInfoVo.getEditUserInfoValuesVos();
        for(EditUserInfoValuesVo euv: editUserInfoValuesVos){
            // 1姓名 2身份证号 3电话号 4家庭住址 5家庭成员数量 6性别
            String editType = euv.getEditType();
            String oldValue = euv.getOldValue();
            String newValue = euv.getNewValue();

            switch (editType){
                case "1":
                    farmerUser.setFarmerName(newValue);
                    sb.append("将姓名由\""+oldValue+"\"修改为\""+newValue+"\";");
                    break;
                case "2":
                    farmerUser.setIdCard(newValue);
                    sb.append("将身份证号由\""+oldValue+"\"修改为\""+newValue+"\";");
                    break;
                case "3":
                    farmerUser.setTelephone(newValue);
                    sb.append("将手机号由\""+oldValue+"\"修改为\""+newValue+"\";");
                    break;
                case "4":

                    String oldName = getAddrFullName(oldValue);
                    String newName = getAddrFullName(newValue);
                    farmerUser.setMapId(newValue);
                    farmerUser.setAddress(newName);
                    sb.append("将家庭住址由\""+oldName+"\"修改为\""+newName+"\";");
                    break;
                case "5":
                    farmerUser.setFamilyMembers(Integer.valueOf(newValue));
                    sb.append("将家庭成员数量由"+oldValue+"人修改为"+newValue+"人;");
                    break;
                case "6":
                    farmerUser.setIdCard(newValue);
                    sb.append("将性别由\""+oldValue+"\"修改为\""+newValue+"\";");
                    break;
            }

        }


        farmerUserMapper.updateFarmerUser(farmerUser);
        String details = sb.toString();
        operationLog.setDetails(details);
        operationLogMapper.insertOperationLog(operationLog);
    }

    /**
     * 查询farmer列表
     * @param farmerUser
     * @return
     */
    @Override
    public List<FarmerUser> selectFarmerUser(FarmerUser farmerUser) {
        List<FarmerUser> farmerUsers = farmerUserMapper.selectFarmerUser(farmerUser);
        return farmerUsers;
    }

    /**
     * 查询farmer详细信息
     * @param farmerId
     * @return
     */
    @Override
    public FarmerUser selectFarmerUserDetail(Long farmerId) {
        FarmerUser farmerUser = new FarmerUser();
        farmerUser.setFarmerId(farmerId);
        List<FarmerUser> farmerUsers = farmerUserMapper.selectFarmerUser(farmerUser);
        if(farmerUsers.size()==0){
            throw new GlobalException("未查询到此农户信息");
        }
        farmerUser = farmerUsers.get(0);
        String mapId = farmerUser.getMapId();
        Map mapIds = this.getMapIds(mapId);
        farmerUser.setSelectMap(mapIds);
        return farmerUser;
    }

    /**
     * 获取所有父节点地址信息
     * @param mapId
     * @return
     */
    @Override
    public Map getMapIds(String mapId){
        Map result = new HashMap();

        Map map = farmerUserMapper.selectAddrById(mapId);
        if(map == null){
            return null;
        }
        String id = (String) map.get("id");
        String parent = (String) map.get("parent");
        Integer level = (Integer)map.get("level");
        String label = (String) map.get("label");
        String pId = parent;
        result.put(level,map);
        //String allMapId = parent + "-" + id;
        for(int i = level-1; i > 0; i--){
            Map p = farmerUserMapper.selectAddrById(pId);
            if(p==null){
                break;
            }
            pId =(String) p.get("parent");
            result.put(i,p);
            //allMapId = pId + "-" + allMapId;
        }
        System.out.println(result);
        return result;
    }

    @Override
    public String getAddrFullName(String mapId) {
        String fullName = "";
        Map map = farmerUserMapper.selectAddrById(mapId);

        String parent = (String) map.get("parent");
        Integer level = (Integer)map.get("level");
        String label = (String) map.get("label");
        String pId = parent;
        fullName = label;
        //String allMapId = parent + "-" + id;
        for(int i = level-1; i > 0; i--){
            Map p = farmerUserMapper.selectAddrById(pId);
            pId =(String) p.get("parent");
            label =(String) p.get("label");
            fullName = label + fullName;
        }
        System.out.println(fullName);
        return fullName;
    }

    @Override
    public List<OperationLog> selectUserOperationLogs(Long farmerUserId) {
        OperationLog operationLog = new OperationLog();
        operationLog.setFarmerUserId(farmerUserId);
        List<OperationLog> operationLogs = operationLogMapper.selectOperationLog(operationLog);
        return operationLogs;
    }

    /**
     * 用户修改手机号
     * @param m
     */
    @Transactional
    @Override
    public void changeFamerUserTel(Map m) {
        //校验验证码
        String newTel = (String)m.get("newtel");//新手机号
        String telephone = (String)m.get("telephone");//数据库原手机号
        String oldTel = (String)m.get("oldtel");//用户输入原手机号
        String code = (String)m.get("code");
        String uuid = (String)m.get("uuid");
        Long userId = (Long)m.get("userId");
        if (!telephone.equals(oldTel)) {
            throw new GlobalException("您输入的原手机号码与登录手机号码不符！");
        }
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(oldTel + uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        if (captcha == null)
        {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException();
        }
        redisCache.deleteObject(verifyKey);

        FarmerUser farmerUser = new FarmerUser();
        farmerUser.setTelephone(oldTel);
        List<FarmerUser> farmerUsers = farmerUserMapper.selectFarmerUser(farmerUser);
        //韩滨说手机号相同的farmerUser同时改240105
        //1、修改farmerUser信息
        for(FarmerUser farmer: farmerUsers){
            farmer.setTelephone(newTel);
            farmerUserMapper.updateFarmerUser(farmer);
        }

        //2、修改用户信息
        SysUser user = new SysUser();
        user.setUserId(userId);
        user.setUpdateBy(user.getUserId()+"");
        user.setUserName(newTel);
        user.setTelephoneNumber(newTel);
        userMapper.updateUser(user);

    }


}
